import schedule
import time
import log
from datetime import datetime
import scraper
import database

# 配置日志
log.basicConfig(
    level=log.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[log.FileHandler("weather_scheduler.log"), log.StreamHandler()]
)
logger = log.getLogger("weather_scheduler")

# 要定期抓取的城市列表
CITIES = ["beijing", "shanghai", "guangzhou", "shenzhen", "chengdu", "hangzhou"]


def daily_update():
    """每日更新天气数据"""
    logger.info("Starting daily weather update...")

    current_month = datetime.now().strftime("%Y%m")

    try:
        # 抓取当前月份的数据
        results = scraper.bulk_scrape(CITIES, [current_month])

        # 导入数据库
        record_count = database.load_json_to_db()

        logger.info(f"Daily update completed: {record_count} records loaded")

        return {
            "status": "success",
            "cities": len(CITIES),
            "records": record_count,
            "results": results
        }

    except Exception as e:
        logger.error(f"Error in daily update: {e}")
        return {
            "status": "error",
            "message": str(e)
        }


def monthly_update():
    """每月初更新上个月的完整数据"""
    logger.info("Starting monthly weather update...")

    # 计算上个月的年月
    now = datetime.now()

    if now.month == 1:
        last_month = f"{now.year - 1}12"
    else:
        last_month = f"{now.year}{now.month - 1:02d}"

    try:
        # 抓取上月数据
        results = scraper.bulk_scrape(CITIES, [last_month])

        # 导入数据库
        record_count = database.load_json_to_db()

        logger.info(f"Monthly update completed: {record_count} records loaded for {last_month}")

        return {
            "status": "success",
            "month": last_month,
            "cities": len(CITIES),
            "records": record_count,
            "results": results
        }

    except Exception as e:
        logger.error(f"Error in monthly update: {e}")
        return {
            "status": "error",
            "message": str(e)
        }


if __name__ == "__main__":
    # 安排定时任务
    # 每天早上6点更新数据
    schedule.every().day.at("06:00").do(daily_update)

    # 每月1号更新上个月的完整数据
    schedule.every().month.at("04:00").do(monthly_update)

    logger.info("Weather scheduler started")

    # 启动时先运行一次更新
    daily_update()

    # 运行调度器
    while True:
        schedule.run_pending()
        time.sleep(60)